using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
public class Player : NetworkBehaviour
{
    private Rigidbody rb;
    private NetworkAnimator animator;
    [SerializeField]
    private float moveSpeed = 10;
    [SerializeField]
    private float turnSpeed = 100;
    [SerializeField]
    private Text nameLabel;
    
    //同步变量
    // private NetworkVariable<Vector3> netPlayerPos = new NetworkVariable<Vector3>(Vector3.zero);
    // private NetworkVariable<Quaternion> netPlayerRot = new NetworkVariable<Quaternion>(Quaternion.identity);
    private NetworkVariable<int> netClientId = new NetworkVariable<int>(0);
    //private NetworkVariable<bool> netWalkState = new NetworkVariable<bool>(false);//行走动画的同步
    
    private Color[] playerColors = new Color[] { Color.red, Color.green, Color.blue, Color.yellow };
    private bool lastWalkState = false;
    void Start()
    {
        animator = GetComponent<NetworkAnimator>();
        rb = GetComponent<Rigidbody>();
        if (this.IsClient && this.IsOwner)
        {
            //只会影响自己角色的位置
            transform.position = new Vector3(Random.Range(-5, 5), 0f, Random.Range(-5, 5));
        }
        nameLabel.text = netClientId.Value.ToString();
        // Renderer renderer = GetComponent<Renderer>();
        // renderer.material.color = playerColors[netClientId.Value % playerColors.Length];
    }
    /// 网络组件被创建的时候，在Start之前被调用
    public override void OnNetworkSpawn()
    {
        Debug.Log("OnNetworkSpawn " + (int)OwnerClientId);
        if (IsServer)
        {
            //这个值拿到以后就会分发给所有客户端
            netClientId.Value = (int)OwnerClientId;
        }
    }
    void Update()
    {
        if (this.IsClient && this.IsOwner)
        {
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");
            //UpdatePosAndRotServerRpc(pos, rotation);
            if (this.IsClient && this.IsOwner)
            {
                //IsOwner是我本人可以操作的对象
                if (v != 0)
                {
                    Vector3 pos = rb.position + transform.forward * v * moveSpeed * Time.deltaTime;
                    rb.MovePosition(pos);
                    Debug.Log($"{pos}   {v}");
                }
                if (h != 0)
                {
                    Quaternion rotation = rb.rotation * Quaternion.Euler(0, h * turnSpeed * Time.deltaTime, 0);
                    rb.MoveRotation(rotation);
                }
            }
            bool walkState = IsTargetWalk(v, h);
            if (lastWalkState != walkState)
            {
                AniWalk(walkState);
                lastWalkState = walkState;
                //UpdateWalkStateServerRpc(walkState);
            }
        } else
        {
            //别的客户端的自己
            // rb.MovePosition(netPlayerPos.Value);
            // rb.MoveRotation(netPlayerRot.Value);
            //其他客户端的自己在接受到net变量的变化之后，在Update里面播放动画
            // if (lastWalkState != netWalkState.Value)
            // {
            //     lastWalkState = netWalkState.Value;
            //     AniWalk(netWalkState.Value);
            // }
        }
    }
    private void AniWalk(bool walk)
    {
        animator.SetTrigger("walk");
    }
    private bool IsTargetWalk(float v, float h)
    {
        return v != 0;
    }
    //NetworkVariable的修改必须在服务器端修改,函数后缀必须以ServerRpc作为结束
    [ServerRpc]
    public void UpdatePosAndRotServerRpc(Vector3 pos, Quaternion rot)
    {
        // netPlayerPos.Value = pos;
        // netPlayerRot.Value = rot;
    }
    [ServerRpc]
    private void UpdateWalkStateServerRpc(bool walkState)
    {
        //netWalkState.Value = walkState;
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Coin"))
        {
            if (IsOwner)
            {
                Debug.Log("OnTriggerEnter");
                Coin coin = other.gameObject.GetComponent<Coin>();
                coin.SetActive(false);
            }
        } else if (other.gameObject.CompareTag("Player"))
        {
            //A通过ServerRpc通知服务器，服务器通过ClientRpc通知B
            //点对点
            if (IsClient && IsOwner)
            {
                //是不是我自己撞击的
                ulong clientId = other.GetComponent<NetworkObject>().OwnerClientId;
                UpdatePlayerMeetServerRpc(this.OwnerClientId, clientId);
            }
        }
    }
    [ServerRpc]
    void UpdatePlayerMeetServerRpc(ulong from, ulong to)
    {
        ClientRpcParams p = new ClientRpcParams()
        {
            Send = new ClientRpcSendParams()
            {
                TargetClientIds = new ulong[] { to } // Send to clients with these IDs
            }
        };
        //NetworkVariable是通知所有客户端的，而这个是通知一个客户端
        NotifyPlayerMeetClientRpc(from, p);
    }
    [ClientRpc]
    void NotifyPlayerMeetClientRpc(ulong from, ClientRpcParams p)
    {
        if (!this.IsOwner)
        {
            Debug.Log("Meet by player:" + from);
        }
    }
}